package com.fjec.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beust.jcommander.StringKey;
import com.carrotsearch.hppc.cursors.ObjectDoubleCursor;
import com.fjec.common.setting.Setting;
import com.fjec.market.entity.BizSubPhysicalOrder;
import com.fjec.market.feign.BaseClient;
import com.fjec.market.feign.PaidClient;
import com.fjec.market.mapper.BizSubPhysicalOrderMapper;
import com.fjec.market.mapper.InfoYsepayRegisterMapper;
import com.fjec.market.service.IBizSubPhysicalOrderService;
import com.fjec.market.service.IInfoYsepayRegisterService;
import org.apache.commons.collections.MapUtils;
import org.apache.xerces.xs.datatypes.ObjectList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 042.实物子订单表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-09-21
 */
@Service
public class BizSubPhysicalOrderServiceImpl extends ServiceImpl<BizSubPhysicalOrderMapper, BizSubPhysicalOrder> implements IBizSubPhysicalOrderService {

    @Resource
    private BizSubPhysicalOrderMapper mapper;

    @Resource
    private InfoYsepayRegisterMapper infoYsepayRegisterMapper;

    @Autowired
    private PaidClient paidClient;

    @Autowired
    private BaseClient baseClient;

    @Override
    public List<Map<String, Object>> getMyDividings(Long busiId, Page page) {
        // 获取该商户所有已签收4 的订单
//        o.Id as orderId,
//        o.PaymentId as paymentId,
//        so.Id as subOrderId,
//        o.OrderType as orderType,
//        o.BuyerShopName as buyerName,
//        json_extract(so.SkuSnapshot, '$.skuTitle') as skuName,
//        json_extract(so.SkuSnapshot, '$.retailSpec') as retailSpec,
//        json_extract(so.SkuSnapshot, '$.retailPrice') as retailPrice,
//        json_extract(so.SkuSnapshot, '$.wholesaleUnit') as wholesaleUnit,
//        json_extract(so.SkuSnapshot, '$.wholesalePrice') as wholesalePrice,
//        json_extract(so.SkuSnapshot, '$.strPics') as skuPic,
//        so.Num as skuNum,
//        so.RealAmount as realAmount,
//        so.HasRefund as hasRefund,
//        so.DistStatus as distStatus
        List<Map<String, Object>> signedSubOrders = mapper.getSignedSubOrders(busiId, page);
        List<Long> paymentIds = signedSubOrders.stream()
                .map(so -> MapUtils.getLong(so, "paymentId"))
                .collect(Collectors.toList());
        List<Long> subOrderIds = signedSubOrders.stream()
                .map(so -> MapUtils.getLong(so, "subOrderId"))
                .collect(Collectors.toList());

        // 获取分账信息
        List<Map<String, Object>> distInfos = paidClient.getDistInfosByPaymentIds(paymentIds);
        // 获取退款信息
        List<Map<String, Object>> refundInfos = paidClient.getRefundInfosBySubOrderIds(subOrderIds);

        // 获取分账比例
        Map<String, Object> settingMap = baseClient.getSysSetting();
        Setting setting = new Setting(settingMap);

        signedSubOrders.forEach(so -> {
            Integer orderType = MapUtils.getInteger(so, "orderType");
            String paymentId = MapUtils.getString(so, "paymentId");
            Integer distStatus = MapUtils.getInteger(so, "distStatus");
            if (distStatus == 2) {
                Optional<Map<String, Object>> od = distInfos.stream()
                        .filter(dist -> MapUtils.getString(dist, "PaymentId").equals(paymentId))
                        .findFirst();
                if (od.isPresent()) {
                    // 分账信息
                    Map<String, Object> d = od.get();
                    Integer realDistStatus = MapUtils.getInteger(d, "DistStatus");
                    if (realDistStatus == 2) {
                        so.put("distStatus", 1);
                        so.put("distTime", MapUtils.getString(d, "CreateTime"));

                        double shopDivision = MapUtils.getDoubleValue(d, "ShopDivision");
                        double platformDivision = MapUtils.getDoubleValue(d, "PlatformDivision");

                        String accountTime = MapUtils.getString(d, "AccountTime");
                        accountTime = accountTime.substring(0, 4) + "-" + accountTime.substring(4, 6) + "-" + accountTime.substring(6);
                        so.put("accountTime", accountTime);
                        // 退款信息
                        Long subOrderId = MapUtils.getLong(so, "subOrderId");
                        Optional<Map<String, Object>> or = refundInfos.stream()
                                .filter(refund -> MapUtils.getLong(refund, "SubOrderId").equals(subOrderId))
                                .findFirst();
                        if (or.isPresent()) {
                            Map<String, Object> r = or.get();
                            Integer refundAmount = MapUtils.getInteger(r, "Payment");
                            so.put("refundAmount", refundAmount);

                            double commission;
                            if (orderType == 1) {
                                commission = Double.parseDouble(setting.getFruitsRetailCommission());
                            } else {
                                commission = Double.parseDouble(setting.getFruitsBatchCommission());
                            }
                            Integer distTotalAmount = MapUtils.getInteger(d, "TotalAmount");
                            Integer distAmount = distTotalAmount - refundAmount;
                            shopDivision = distAmount.doubleValue() * (1 - commission);
                            shopDivision = Math.round(shopDivision);
                            platformDivision = distAmount - shopDivision;
                            so.put("shopDivision", (int) shopDivision);
                            so.put("platformDivision", (int) platformDivision);
                        } else {
                            so.put("refundAmount", 0);
                            so.put("shopDivision", (int) (shopDivision * 100));
                            so.put("platformDivision", (int) (platformDivision * 100));
                        }

                    } else {
                        so.put("distStatus", 0);
                    }

                }
            } else {
                so.put("distStatus", 0);
            }
        });


        return signedSubOrders;
    }

    @Override
    public Map<String, Object> getMyDividingsStat(Long busiId) {
        Map<String, Object> result = new HashMap<>();
        // 待结算订单数
        int numToDivide = mapper.getNumToDivide(busiId);
        result.put("numToDivide", numToDivide);

        // 已结算金额
        String payeeUserCode = infoYsepayRegisterMapper.getUserCodeByBusiId(busiId);
        int totalAccountAmount = paidClient.getTotalAccountAmount(payeeUserCode);
        result.put("totalAccountAmount", totalAccountAmount);

        return result;
    }

    @Override
    public int setDistStatusAccounted(Long paymentId) {
        mapper.setDistStatusAccounted(paymentId);
        return 0;
    }
}
